<template>
  <div class="adoption-container">
    <el-card class="page-card" shadow="hover">
      <!-- 页面标题 -->
      <div class="header">
        <div class="header-content">
          <h2 class="page-title">
            <el-icon><Document /></el-icon>
            <span>领养管理</span>
          </h2>
          <div class="subtitle">查看申请记录和申请新领养</div>
        </div>
      </div>

      <!-- 标签页切换 -->
      <el-tabs v-model="activeTab" type="card" class="adoption-tabs">
        <!-- 我的申请记录 -->
        <el-tab-pane label="我的申请记录" name="records">
          <!-- 筛选区域 -->
          <div class="filter-section">
            <el-row :gutter="16">
              <el-col :span="6">
                <el-select
                  v-model="filters.status"
                  placeholder="申请状态"
                  clearable
                  @change="handleFilter"
                  style="width: 100%"
                >
                  <el-option label="全部状态" :value="null" />
                  <el-option label="待审核" :value="0" />
                  <el-option label="已通过" :value="1" />
                  <el-option label="已驳回" :value="2" />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-input
                  v-model="filters.animalName"
                  placeholder="搜索动物名称"
                  clearable
                  @clear="handleFilter"
                  @keyup.enter="handleFilter"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </el-col>
              <el-col :span="6">
                <el-button type="primary" @click="handleFilter" :icon="Search">
                  筛选
                </el-button>
                <el-button @click="handleReset" :icon="Refresh">
                  重置
                </el-button>
              </el-col>
            </el-row>
          </div>

          <!-- 申请记录表格 -->
          <el-table 
            :data="filteredRecords" 
            border 
            stripe 
            style="width: 100%" 
            class="records-table"
            v-loading="loading"
          >
            <el-table-column prop="id" label="申请编号" width="120" align="center">
              <template #default="{ row }">
                <span class="code-text">#{{ row.id }}</span>
              </template>
            </el-table-column>
            <el-table-column label="动物信息" width="200">
              <template #default="{ row }">
                <div class="animal-info-cell" v-if="row.animal">
                  <img 
                    v-if="row.animal.photo" 
                    :src="row.animal.photo" 
                    class="animal-thumb"
                    @click="goAnimalDetail(row.animal.id || row.animalId)"
                  />
                  <div class="animal-details">
                    <div class="animal-name-link" @click="goAnimalDetail(row.animal.id || row.animalId)">
                      {{ row.animal.name || '未命名' }}
                    </div>
                    <div class="animal-meta">{{ row.animal.species || '未知' }} · {{ row.animal.gender || '未知' }}</div>
                  </div>
                </div>
                <div v-else-if="row.animalId" class="animal-info-cell">
                  <el-button 
                    size="small" 
                    type="primary" 
                    text
                    @click="goAnimalDetail(row.animalId)"
                  >
                    查看动物 #{{ row.animalId }}
                  </el-button>
                </div>
                <span v-else class="text-muted">动物信息已删除</span>
              </template>
            </el-table-column>
            <el-table-column prop="applicantName" label="申请人" width="120" align="center">
              <template #default="{ row }">
                <span>{{ row.applicantName || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="联系电话" width="140" align="center" />
            <el-table-column prop="address" label="居住地址" min-width="150">
              <template #default="{ row }">
                <span 
                  v-if="row.address && row.address.length > 15"
                  class="clickable-text"
                  @click="showDetailDialog('居住地址', row.address)"
                >
                  {{ row.address.substring(0, 15) }}...
                  <el-icon class="view-icon"><View /></el-icon>
                </span>
                <span v-else-if="row.address" class="clickable-text" @click="showDetailDialog('居住地址', row.address)">
                  {{ row.address }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="housingType" label="住房情况" width="120" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.housingType" type="info" size="small" class="clickable-tag" @click="showDetailDialog('住房情况', row.housingType)">
                  {{ row.housingType }}
                  <el-icon class="view-icon"><View /></el-icon>
                </el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="familyMembers" label="家庭成员" width="150">
              <template #default="{ row }">
                <span 
                  v-if="row.familyMembers && row.familyMembers.length > 10"
                  class="clickable-text"
                  @click="showDetailDialog('家庭成员', row.familyMembers)"
                >
                  {{ row.familyMembers.substring(0, 10) }}...
                  <el-icon class="view-icon"><View /></el-icon>
                </span>
                <span v-else-if="row.familyMembers" class="clickable-text" @click="showDetailDialog('家庭成员', row.familyMembers)">
                  {{ row.familyMembers }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="领养理由" min-width="180">
              <template #default="{ row }">
                <span 
                  v-if="row.reason && row.reason.length > 20"
                  class="clickable-text"
                  @click="showDetailDialog('领养理由', row.reason)"
                >
                  {{ row.reason.substring(0, 20) }}...
                  <el-icon class="view-icon"><View /></el-icon>
                </span>
                <span v-else-if="row.reason" class="clickable-text" @click="showDetailDialog('领养理由', row.reason)">
                  {{ row.reason }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="experience" label="养宠经验" min-width="180">
              <template #default="{ row }">
                <span 
                  v-if="row.experience && row.experience.length > 20"
                  class="clickable-text"
                  @click="showDetailDialog('养宠经验', row.experience)"
                >
                  {{ row.experience.substring(0, 20) }}...
                  <el-icon class="view-icon"><View /></el-icon>
                </span>
                <span v-else-if="row.experience" class="clickable-text" @click="showDetailDialog('养宠经验', row.experience)">
                  {{ row.experience }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="110" align="center">
              <template #default="{ row }">
                <el-tag 
                  v-if="row.status === 0" 
                  type="warning"
                  effect="dark"
                >
                  待审核
                </el-tag>
                <el-tag 
                  v-else-if="row.status === 1" 
                  type="success"
                  effect="dark"
                >
                  已通过
                </el-tag>
                <el-tag 
                  v-else 
                  type="danger"
                  effect="dark"
                >
                  已驳回
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="applyTime" label="申请时间" width="180" align="center">
              <template #default="{ row }">
                <div class="time-cell">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatTime(row.applyTime) }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="reviewTime" label="审核时间" width="180" align="center">
              <template #default="{ row }">
                <div class="time-cell">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatTime(row.reviewTime) || '-' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="驳回理由" width="200" v-if="filteredRecords.some(r => r.status === 2)">
              <template #default="{ row }">
                <span v-if="row.status === 2 && (row.rejectReason || row.rejectreason)" class="reject-reason">
                  {{ row.rejectReason || row.rejectreason }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220" align="center" fixed="right">
              <template #default="{ row }">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="goAnimalDetail(row.animalId || row.animal?.id)"
                  :disabled="!row.animalId && !row.animal"
                >
                  <el-icon><View /></el-icon>
                  查看
                </el-button>
                <el-button 
                  v-if="row.status === 0"
                  size="small" 
                  type="warning"
                  @click="openEditDialog(row)"
                >
                  <el-icon><EditPen /></el-icon>
                  编辑
                </el-button>
                <el-button 
                  v-if="row.status === 0"
                  size="small" 
                  type="danger"
                  @click="handleWithdraw(row)"
                >
                  <el-icon><Delete /></el-icon>
                  撤回
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 空状态 -->
          <el-empty 
            v-if="!loading && filteredRecords.length === 0 && originalRecords.length === 0" 
            description="暂无申请记录" 
            :image-size="150" 
          />
          <el-empty 
            v-else-if="!loading && filteredRecords.length === 0" 
            description="没有找到符合条件的记录" 
            :image-size="150" 
          />
        </el-tab-pane>

        <!-- 申请新领养 -->
        <el-tab-pane label="申请新领养" name="apply">
          <!-- 选择动物 -->
          <div class="animal-selection-section">
            <h3 class="section-title">
              <el-icon><Files /></el-icon>
              选择要领养的动物
            </h3>
            
            <!-- 动物筛选 -->
            <div class="filter-section">
              <el-row :gutter="16">
                <el-col :span="6">
                  <el-input
                    v-model="animalFilters.keyword"
                    placeholder="搜索动物名称"
                    clearable
                    @clear="handleAnimalFilter"
                    @keyup.enter="handleAnimalFilter"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="4">
                  <el-select
                    v-model="animalFilters.species"
                    placeholder="种类"
                    clearable
                    @change="handleAnimalFilter"
                    style="width: 100%"
                  >
                    <el-option label="全部种类" :value="''" />
                    <el-option label="猫" value="猫" />
                    <el-option label="狗" value="狗" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </el-col>
                <el-col :span="4">
                  <el-select
                    v-model="animalFilters.gender"
                    placeholder="性别"
                    clearable
                    @change="handleAnimalFilter"
                    style="width: 100%"
                  >
                    <el-option label="全部性别" :value="''" />
                    <el-option label="公" value="公" />
                    <el-option label="母" value="母" />
                  </el-select>
                </el-col>
                <el-col :span="6">
                  <el-button type="primary" @click="handleAnimalFilter" :icon="Search">
                    筛选
                  </el-button>
                  <el-button @click="handleAnimalReset" :icon="Refresh">
                    重置
                  </el-button>
                </el-col>
              </el-row>
            </div>

            <!-- 动物列表 -->
            <el-row :gutter="20" v-if="filteredAnimals.length > 0" class="animals-grid">
              <el-col 
                :span="6" 
                v-for="animal in filteredAnimals" 
                :key="animal.id"
              >
                <el-card 
                  shadow="hover" 
                  class="animal-card"
                  :class="{ 'selected': selectedAnimal?.id === animal.id }"
                  @click="selectAnimal(animal)"
                >
                  <div class="animal-image-wrapper">
                    <img 
                      :src="animal.photo" 
                      :alt="animal.name" 
                      class="animal-img"
                    />
                    <div class="status-badge">
                      <el-tag 
                        :type="getAnimalStatusType(animal.status)" 
                        size="small"
                        effect="dark"
                      >
                        {{ getAnimalStatusText(animal.status) }}
                      </el-tag>
                    </div>
                  </div>
                  <div class="animal-info">
                    <h4 class="animal-name">{{ animal.name || '未命名' }}</h4>
                    <div class="animal-meta">
                      <span>{{ animal.species }}</span>
                      <span>{{ animal.gender }}</span>
                      <span v-if="animal.age">{{ animal.age }}</span>
                    </div>
                  </div>
                  <div class="select-indicator" v-if="selectedAnimal?.id === animal.id">
                    <el-icon><Check /></el-icon>
                    已选择
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <el-empty 
              v-else 
              description="暂无待领养动物" 
              :image-size="150"
              v-loading="animalsLoading"
            />
          </div>

          <!-- 选择动物后的操作提示 -->
          <div v-if="selectedAnimal" class="selected-animal-action">
            <el-card class="action-card" shadow="hover">
              <div class="action-content">
                <div class="selected-preview">
                  <img :src="selectedAnimal.photo" :alt="selectedAnimal.name" class="preview-img" />
                  <div class="preview-info">
                    <h4>{{ selectedAnimal.name || '未命名' }}</h4>
                    <div class="tags">
                      <el-tag type="info" size="small">
                        <el-icon><Collection /></el-icon>
                        {{ selectedAnimal.species }}
                      </el-tag>
                      <el-tag type="info" size="small">
                        <el-icon><User /></el-icon>
                        {{ selectedAnimal.gender }}
                      </el-tag>
                      <el-tag v-if="selectedAnimal.age" type="info" size="small">
                        <el-icon><Timer /></el-icon>
                        {{ selectedAnimal.age }}
                      </el-tag>
                    </div>
                  </div>
                </div>
                <div class="action-buttons">
                  <el-button type="primary" size="large" @click="openAdoptionDialog">
                    <el-icon><EditPen /></el-icon>
                    填写领养申请
                  </el-button>
                  <el-button size="large" @click="clearSelection">
                    <el-icon><Close /></el-icon>
                    取消选择
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>

          <div v-else class="no-selection-tip">
            <el-alert
              title="请先选择要领养的动物"
              type="info"
              :closable="false"
              show-icon
            >
              <template #default>
                <p>在上方动物列表中点击选择一个动物，然后点击"填写领养申请"按钮。</p>
              </template>
            </el-alert>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 领养申请对话框 -->
    <el-dialog
      v-model="adoptionDialogVisible"
      title="填写领养申请信息"
      width="750px"
      :close-on-click-modal="false"
    >
      <!-- 选中的动物信息 -->
      <div class="dialog-animal-info" v-if="selectedAnimal">
        <div class="animal-preview-card">
          <img :src="selectedAnimal.photo" :alt="selectedAnimal.name" class="dialog-animal-img" />
          <div class="dialog-animal-details">
            <h4>
              <el-icon><Star /></el-icon>
              {{ selectedAnimal.name || '未命名' }}
            </h4>
            <div class="dialog-tags">
              <el-tag type="info" size="small">
                <el-icon><Collection /></el-icon>
                {{ selectedAnimal.species }}
              </el-tag>
              <el-tag type="info" size="small">
                <el-icon><User /></el-icon>
                {{ selectedAnimal.gender }}
              </el-tag>
              <el-tag v-if="selectedAnimal.age" type="info" size="small">
                <el-icon><Timer /></el-icon>
                {{ selectedAnimal.age }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>

      <el-form 
        :model="adoptionForm" 
        :rules="formRules" 
        ref="adoptionFormRef"
        label-width="120px"
        label-position="left"
        class="adoption-form-dialog"
      >
        <el-form-item label="申请人姓名" prop="applicantName">
          <el-input 
            v-model="adoptionForm.applicantName" 
            placeholder="请输入您的姓名"
            clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input 
            v-model="adoptionForm.phone" 
            placeholder="请输入联系电话"
            clearable
            maxlength="11"
          >
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="居住地址" prop="address">
          <el-input 
            v-model="adoptionForm.address" 
            placeholder="请输入详细居住地址"
            clearable
          >
            <template #prefix>
              <el-icon><Location /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="住房情况" prop="housingType">
          <el-select 
            v-model="adoptionForm.housingType" 
            placeholder="请选择住房情况"
            clearable
            style="width: 100%"
          >
            <el-option label="自有住房" value="自有住房">
              <span style="display: flex; align-items: center; gap: 6px;">
                <el-icon><House /></el-icon>
                <span>自有住房</span>
              </span>
            </el-option>
            <el-option label="租房" value="租房">
              <span style="display: flex; align-items: center; gap: 6px;">
                <el-icon><Key /></el-icon>
                <span>租房</span>
              </span>
            </el-option>
            <el-option label="其他" value="其他">
              <span style="display: flex; align-items: center; gap: 6px;">
                <el-icon><MoreFilled /></el-icon>
                <span>其他</span>
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="家庭成员" prop="familyMembers">
          <el-input 
            v-model="adoptionForm.familyMembers" 
            placeholder="请输入家庭成员情况（如：夫妻+1个孩子）"
            clearable
          >
            <template #prefix>
              <el-icon><UserFilled /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="领养理由" prop="reason">
          <el-input 
            type="textarea" 
            v-model="adoptionForm.reason" 
            :rows="5"
            placeholder="请详细说明您想领养此动物的理由，以及您能为它提供的照顾..."
            maxlength="999"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="养宠经验" prop="experience">
          <el-input 
            type="textarea" 
            v-model="adoptionForm.experience" 
            :rows="4"
            placeholder="请说明您是否有养宠经验，如果有，请简要描述..."
            maxlength="999"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeAdoptionDialog">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
        <el-button type="primary" @click="submitAdoption" :loading="submitting">
          <el-icon><Check /></el-icon>
          提交申请
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="detailTitle"
      width="600px"
      :close-on-click-modal="true"
    >
      <div class="detail-content">
        <el-icon class="detail-icon"><Document /></el-icon>
        <div class="detail-text">{{ detailContent }}</div>
      </div>
      <template #footer>
        <el-button type="primary" @click="detailDialogVisible = false">
          <el-icon><Check /></el-icon>
          关闭
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑申请对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑申请信息"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="editForm" 
        :rules="formRules" 
        ref="editFormRef"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="申请人姓名" prop="applicantName">
          <el-input 
            v-model="editForm.applicantName" 
            placeholder="请输入您的姓名"
            clearable
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input 
            v-model="editForm.phone" 
            placeholder="请输入联系电话"
            clearable
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="居住地址" prop="address">
          <el-input 
            v-model="editForm.address" 
            placeholder="请输入详细居住地址"
            clearable
          />
        </el-form-item>

        <el-form-item label="住房情况" prop="housingType">
          <el-select 
            v-model="editForm.housingType" 
            placeholder="请选择住房情况"
            clearable
            style="width: 100%"
          >
            <el-option label="自有住房" value="自有住房" />
            <el-option label="租房" value="租房" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="家庭成员" prop="familyMembers">
          <el-input 
            v-model="editForm.familyMembers" 
            placeholder="请输入家庭成员情况（如：夫妻+1个孩子）"
            clearable
          />
        </el-form-item>

        <el-form-item label="领养理由" prop="reason">
          <el-input 
            type="textarea" 
            v-model="editForm.reason" 
            :rows="5"
            placeholder="请详细说明您想领养此动物的理由，以及您能为它提供的照顾..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="养宠经验" prop="experience">
          <el-input 
            type="textarea" 
            v-model="editForm.experience" 
            :rows="4"
            placeholder="请说明您是否有养宠经验，如果有，请简要描述..."
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdate" :loading="updating">
          <el-icon><Check /></el-icon>
          保存修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { 
  Document, Search, Refresh, Clock, Check, Files, EditPen, View, Delete,
  Collection, User, Timer, Close, Star, Phone, Location, House, Key,
  MoreFilled, UserFilled
} from '@element-plus/icons-vue';

export default {
  components: {
    Document,
    Search,
    Refresh,
    Clock,
    Check,
    Files,
    EditPen,
    View,
    Delete,
    Collection,
    User,
    Timer,
    Close,
    Star,
    Phone,
    Location,
    House,
    Key,
    MoreFilled,
    UserFilled
  },
  data() {
    // 手机号验证
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入联系电话'));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };

    return {
      activeTab: 'records',
      loading: false,
      animalsLoading: false,
      submitting: false,
      updating: false,
      
      // 申请记录相关
      originalRecords: [],
      filters: {
        status: null,
        animalName: ''
      },
      
      // 领养申请对话框相关
      adoptionDialogVisible: false,
      
      // 详情对话框相关
      detailDialogVisible: false,
      detailTitle: '',
      detailContent: '',
      
      // 编辑对话框相关
      editDialogVisible: false,
      editForm: {
        id: null,
        userId: null,
        animalId: null,
        applicantName: '',
        phone: '',
        address: '',
        housingType: '',
        familyMembers: '',
        reason: '',
        experience: ''
      },
      
      // 动物选择相关
      originalAnimals: [],
      selectedAnimal: null,
      animalFilters: {
        keyword: '',
        species: '',
        gender: ''
      },
      
      // 领养表单
      adoptionForm: {
        userId: null,
        animalId: null,
        applicantName: '',
        phone: '',
        address: '',
        housingType: '',
        familyMembers: '',
        reason: '',
        experience: ''
      },
      
      formRules: {
        applicantName: [
          { required: true, message: '请输入申请人姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入居住地址', trigger: 'blur' },
          { min: 5, message: '地址至少5个字符', trigger: 'blur' }
        ],
        housingType: [
          { required: true, message: '请选择住房情况', trigger: 'change' }
        ],
        reason: [
          { required: true, message: '请输入领养理由', trigger: 'blur' },
          { min: 300, message: '领养理由至少300个字', trigger: 'blur' }
        ],
        experience: [
          { required: true, message: '请输入养宠经验', trigger: 'blur' },
          { min: 300, message: '养宠经验至少300个字', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    // 筛选后的申请记录
    filteredRecords() {
      let result = [...this.originalRecords];
      
      if (this.filters.status !== null && this.filters.status !== undefined && this.filters.status !== '') {
        result = result.filter(record => record.status === this.filters.status);
      }
      
      if (this.filters.animalName) {
        const keyword = this.filters.animalName.toLowerCase();
        result = result.filter(record => {
          if (record.animal && record.animal.name) {
            return record.animal.name.toLowerCase().includes(keyword);
          }
          return false;
        });
      }
      
      return result;
    },
    
    // 筛选后的动物列表（只显示待领养状态）
    filteredAnimals() {
      let result = this.originalAnimals.filter(animal => animal.status === 0); // 0: 待领养
      
      if (this.animalFilters.keyword) {
        const keyword = this.animalFilters.keyword.toLowerCase();
        result = result.filter(animal => 
          (animal.name || '').toLowerCase().includes(keyword)
        );
      }
      
      if (this.animalFilters.species) {
        result = result.filter(animal => animal.species === this.animalFilters.species);
      }
      
      if (this.animalFilters.gender) {
        result = result.filter(animal => animal.gender === this.animalFilters.gender);
      }
      
      return result;
    }
  },
  async mounted() {
    const userId = localStorage.getItem('userId');
    this.adoptionForm.userId = userId;
    
    await this.loadRecords();
    await this.loadAnimals();
  },
  methods: {
    // 加载申请记录
    async loadRecords() {
      this.loading = true;
      try {
        const userId = localStorage.getItem('userId');
        const res = await axios.get(`http://localhost:8080/api/adoption/user/${userId}`);
        if (res.data.code === 200) {
          const records = res.data.data || [];
          // 为每条记录加载对应的动物信息
          for (let record of records) {
            if (record.animalId && !record.animal) {
              try {
                const animalRes = await axios.get(`http://localhost:8080/api/animal/${record.animalId}`);
                if (animalRes.data.code === 200 && animalRes.data.data) {
                  record.animal = animalRes.data.data;
                }
              } catch (error) {
                console.error(`加载动物信息失败 (animalId: ${record.animalId}):`, error);
              }
            }
          }
          this.originalRecords = records;
        } else {
          ElMessage.error('加载申请记录失败');
        }
      } catch (error) {
        console.error('加载申请记录失败:', error);
        ElMessage.error('加载申请记录失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 加载可领养动物列表
    async loadAnimals() {
      this.animalsLoading = true;
      try {
        const res = await axios.get("http://localhost:8080/api/animal/listAll");
        if (res.data.code === 200) {
          this.originalAnimals = res.data.data || [];
        } else {
          ElMessage.error('加载动物列表失败');
        }
      } catch (error) {
        ElMessage.error('加载动物列表失败');
      } finally {
        this.animalsLoading = false;
      }
    },
    
    // 筛选申请记录
    handleFilter() {
      // 筛选逻辑在computed中实现
    },
    
    // 重置申请记录筛选
    handleReset() {
      this.filters = {
        status: null,
        animalName: ''
      };
    },
    
    // 筛选动物
    handleAnimalFilter() {
      // 筛选逻辑在computed中实现
    },
    
    // 重置动物筛选
    handleAnimalReset() {
      this.animalFilters = {
        keyword: '',
        species: '',
        gender: ''
      };
    },
    
    // 选择动物
    selectAnimal(animal) {
      if (animal.status === 0) { // 只有待领养状态才能选择
        this.selectedAnimal = animal;
        this.adoptionForm.animalId = animal.id;
      } else {
        ElMessage.warning('该动物当前不可领养');
      }
    },
    
    // 清除选择
    clearSelection() {
      this.selectedAnimal = null;
      this.adoptionForm.animalId = null;
      this.$refs.adoptionFormRef?.resetFields();
      this.adoptionDialogVisible = false;
    },
    
    // 打开领养申请对话框
    openAdoptionDialog() {
      if (!this.selectedAnimal) {
        ElMessage.warning('请先选择要领养的动物');
        return;
      }
      this.adoptionDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.adoptionFormRef?.clearValidate();
      });
    },
    
    // 关闭领养申请对话框
    closeAdoptionDialog() {
      this.adoptionDialogVisible = false;
    },
    
    // 提交领养申请
    async submitAdoption() {
      if (!this.$refs.adoptionFormRef) return;

      await this.$refs.adoptionFormRef.validate(async (valid) => {
        if (!valid) {
          ElMessage.warning('请完善表单信息');
          return;
        }

        this.submitting = true;
        try {
          const res = await axios.post('http://localhost:8080/api/adoption/apply', this.adoptionForm);
          
          if (res.data.code === 200) {
            ElMessage.success('申请提交成功！我们会尽快审核您的申请');
            
            // 关闭对话框
            this.adoptionDialogVisible = false;
            
            // 清空表单和选择
            this.selectedAnimal = null;
            this.adoptionForm.animalId = null;
            this.$refs.adoptionFormRef?.resetFields();
            
            // 刷新数据
            await this.loadRecords();
            await this.loadAnimals();
            
            // 切换到申请记录标签页
            this.activeTab = 'records';
          } else {
            ElMessage.error(res.data.msg || '提交失败');
          }
        } catch (error) {
          ElMessage.error('提交失败：' + (error.message || '网络错误'));
        } finally {
          this.submitting = false;
        }
      });
    },
    
    // 时间格式化
    formatTime(time) {
      if (!time) return '-';
      
      if (typeof time === 'string') {
        const date = new Date(time);
        if (isNaN(date.getTime())) {
          return time;
        }
        time = date;
      }
      
      if (time instanceof Date) {
        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        const hours = String(time.getHours()).padStart(2, '0');
        const minutes = String(time.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      }
      
      return time;
    },
    
    // 动物状态文本
    getAnimalStatusText(status) {
      const statusTexts = ["待领养", "已领养", "审核中", "待救助", "救助中"];
      return statusTexts[status] || '未知';
    },
    
    // 动物状态类型
    getAnimalStatusType(status) {
      const types = ['success', 'info', 'warning', 'warning', 'info'];
      return types[status] || 'info';
    },
    
    // 跳转到动物详情
    goAnimalDetail(animalId) {
      if (animalId) {
        this.$router.push({
          path: `/user/animal/${animalId}`,
          query: { from: 'adoption' }
        });
      } else {
        ElMessage.warning('动物信息不存在，无法查看详情');
      }
    },
    
    // 打开编辑对话框
    openEditDialog(row) {
      if (row.status !== 0) {
        ElMessage.warning('只有待审核状态的申请才能编辑');
        return;
      }
      
      // 填充编辑表单
      this.editForm = {
        id: row.id,
        userId: row.userId,
        animalId: row.animalId,
        applicantName: row.applicantName || '',
        phone: row.phone || '',
        address: row.address || '',
        housingType: row.housingType || '',
        familyMembers: row.familyMembers || '',
        reason: row.reason || '',
        experience: row.experience || ''
      };
      
      this.editDialogVisible = true;
      
      // 清除表单验证状态
      this.$nextTick(() => {
        this.$refs.editFormRef?.clearValidate();
      });
    },
    
    // 提交更新申请
    async submitUpdate() {
      if (!this.$refs.editFormRef) return;
      
      await this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          ElMessage.warning('请完善表单信息');
          return;
        }
        
        this.updating = true;
        try {
          const res = await axios.put('http://localhost:8080/api/adoption/update', this.editForm);
          
          if (res.data.code === 200) {
            ElMessage.success('申请信息更新成功');
            this.editDialogVisible = false;
            
            // 刷新数据
            await this.loadRecords();
          } else {
            ElMessage.error(res.data.msg || '更新失败');
          }
        } catch (error) {
          console.error('更新申请失败:', error);
          ElMessage.error('更新失败：' + (error.response?.data?.msg || error.message || '网络错误'));
        } finally {
          this.updating = false;
        }
      });
    },
    
    // 显示详情对话框
    showDetailDialog(title, content) {
      if (!content || content === '-') {
        ElMessage.info('该字段暂无内容');
        return;
      }
      this.detailTitle = title;
      this.detailContent = content;
      this.detailDialogVisible = true;
    },
    
    // 撤回申请
    async handleWithdraw(row) {
      if (row.status !== 0) {
        ElMessage.warning('只有待审核状态的申请才能撤回');
        return;
      }
      
      try {
        await ElMessageBox.confirm(
          `确定要撤回申请 #${row.id} 吗？撤回后将无法恢复。`,
          '确认撤回',
          {
            confirmButtonText: '确定撤回',
            cancelButtonText: '取消',
            type: 'warning',
            confirmButtonClass: 'el-button--danger'
          }
        );
        
        // 用户确认，执行撤回
        try {
          const res = await axios.delete(`http://localhost:8080/api/adoption/delete/${row.id}`);
          
          if (res.data.code === 200) {
            ElMessage.success('申请已撤回');
            
            // 刷新数据
            await this.loadRecords();
          } else {
            ElMessage.error(res.data.msg || '撤回失败');
          }
        } catch (error) {
          console.error('撤回申请失败:', error);
          ElMessage.error('撤回失败：' + (error.response?.data?.msg || error.message || '网络错误'));
        }
      } catch (error) {
        // 用户取消
        if (error !== 'cancel') {
          console.error('撤回确认失败:', error);
        }
      }
    }
  }
};
</script>

<style scoped>
.adoption-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100%;
}

.page-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

:deep(.el-card__body) {
  padding: 30px;
}

.header {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0 0 8px 0;
  font-size: 26px;
  font-weight: 600;
  color: #303133;
}

.page-title .el-icon {
  font-size: 32px;
  color: #409eff;
}

.subtitle {
  color: #909399;
  font-size: 14px;
  margin-left: 44px;
}

/* 标签页样式 */
.adoption-tabs {
  margin-top: 20px;
}

:deep(.el-tabs__header) {
  margin-bottom: 24px;
}

:deep(.el-tabs__item) {
  font-size: 15px;
  font-weight: 500;
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.filter-section .el-button {
  margin-left: 8px;
}

/* 申请记录表格 */
.records-table {
  margin-top: 20px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background: #fafafa;
}

:deep(.el-table__header th) {
  background: #fafafa;
  color: #303133;
  font-weight: 600;
}

.code-text {
  font-family: 'Courier New', monospace;
  font-weight: 600;
  color: #409eff;
}

.animal-info-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.animal-thumb {
  width: 50px;
  height: 50px;
  border-radius: 6px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s;
}

.animal-thumb:hover {
  transform: scale(1.1);
}

.animal-details {
  flex: 1;
}

.animal-name-link {
  font-weight: 600;
  color: #409eff;
  cursor: pointer;
  margin-bottom: 4px;
}

.animal-name-link:hover {
  text-decoration: underline;
}

.animal-meta {
  font-size: 12px;
  color: #909399;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  font-size: 14px;
}

.time-cell .el-icon {
  color: #909399;
  font-size: 16px;
}

.reject-reason {
  color: #f56c6c;
  font-size: 13px;
}

.text-muted {
  color: #909399;
  font-size: 13px;
}

/* 可点击文本样式 */
.clickable-text {
  cursor: pointer;
  color: #409eff;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.clickable-text:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.clickable-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.clickable-tag:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.view-icon {
  font-size: 14px;
  margin-left: 4px;
  opacity: 0.7;
}

.clickable-text:hover .view-icon,
.clickable-tag:hover .view-icon {
  opacity: 1;
}

/* 详情对话框样式 */
.detail-content {
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  display: flex;
  align-items: flex-start;
  gap: 16px;
  min-height: 100px;
}

.detail-icon {
  font-size: 32px;
  color: #409eff;
  flex-shrink: 0;
  margin-top: 4px;
}

.detail-text {
  flex: 1;
  font-size: 15px;
  line-height: 1.8;
  color: #303133;
  white-space: pre-wrap;
  word-wrap: break-word;
  word-break: break-all;
}

/* 动物选择区域 */
.animal-selection-section {
  margin-bottom: 30px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0 0 20px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.section-title .el-icon {
  font-size: 24px;
  color: #409eff;
}

.animals-grid {
  margin-top: 20px;
}

.animal-card {
  margin-bottom: 20px;
  cursor: pointer;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
}

.animal-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.animal-card.selected {
  border: 2px solid #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.animal-image-wrapper {
  position: relative;
  width: 100%;
  padding-top: 75%;
  overflow: hidden;
}

.animal-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.animal-card:hover .animal-img {
  transform: scale(1.05);
}

.status-badge {
  position: absolute;
  top: 12px;
  right: 12px;
}

.animal-info {
  padding: 16px;
  text-align: left;
}

.animal-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.animal-meta {
  display: flex;
  gap: 8px;
  font-size: 13px;
  color: #909399;
}

.animal-meta span {
  padding: 2px 8px;
  background: #f5f7fa;
  border-radius: 4px;
}

.select-indicator {
  position: absolute;
  top: 10px;
  left: 10px;
  background: #409eff;
  color: #fff;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 选择动物后的操作提示 */
.selected-animal-action {
  margin-top: 30px;
}

.action-card {
  border-radius: 12px;
  border: 2px solid #409eff;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
}

.action-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 24px;
  padding: 16px;
}

.selected-preview {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.preview-img {
  width: 80px;
  height: 80px;
  border-radius: 12px;
  object-fit: cover;
  border: 3px solid #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.preview-info h4 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.preview-info .tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.preview-info .tags .el-tag {
  display: flex;
  align-items: center;
  gap: 4px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-buttons .el-button {
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 对话框动物信息 */
.dialog-animal-info {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 2px solid #ebeef5;
}

.animal-preview-card {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
}

.dialog-animal-img {
  width: 100px;
  height: 100px;
  border-radius: 12px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  object-fit: cover;
}

.dialog-animal-details h4 {
  margin: 0 0 12px 0;
  font-size: 24px;
  font-weight: 600;
  color: #ffffff;
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.dialog-tags .el-tag {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.3);
  color: #ffffff;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 对话框表单 */
.adoption-form-dialog {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 8px;
}

.adoption-form-dialog :deep(.el-input__prefix) {
  color: #909399;
}

.adoption-form-dialog :deep(.el-select .el-input__prefix) {
  display: none;
}

/* 领养表单区域（已废弃，保留以防万一） */
.adoption-form-section {
  margin-top: 30px;
  padding-top: 30px;
  border-top: 2px solid #ebeef5;
}

.form-card {
  margin-top: 20px;
  border-radius: 12px;
}

.selected-animal-info {
  margin-bottom: 24px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
}

.animal-preview {
  display: flex;
  align-items: center;
  gap: 20px;
}

.animal-preview img {
  width: 100px;
  height: 100px;
  border-radius: 12px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  object-fit: cover;
}

.animal-info-preview h4 {
  margin: 0 0 12px 0;
  font-size: 24px;
  font-weight: 600;
  color: #ffffff;
}

.tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tags :deep(.el-tag) {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.3);
  color: #ffffff;
  font-weight: 500;
}

.no-selection-tip {
  margin-top: 30px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  border-radius: 6px;
}

:deep(.el-input__inner:focus),
:deep(.el-textarea__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.el-select) {
  width: 100%;
}

.el-button--large {
  padding: 12px 28px;
  font-weight: 500;
}

/* 空状态 */
:deep(.el-empty) {
  padding: 60px 0;
}

/* 响应式 */
@media (max-width: 1200px) {
  .animals-grid .el-col {
    width: 50%;
  }
}

@media (max-width: 768px) {
  .adoption-container {
    padding: 10px;
  }
  
  :deep(.el-card__body) {
    padding: 20px;
  }
  
  .filter-section .el-col {
    margin-bottom: 12px;
  }
  
  .animals-grid .el-col {
    width: 100%;
  }
  
  .animal-preview {
    flex-direction: column;
    text-align: center;
  }
  
  .action-content {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: flex-end;
    margin-top: 16px;
  }
  
  .action-buttons .el-button {
    flex: 1;
  }
  
  .animal-preview-card {
    flex-direction: column;
    text-align: center;
  }
  
  .dialog-animal-img {
    margin: 0 auto;
  }
}
</style>
